use std::fmt::Debug;

use clap::Parser;

use crate::runtime::error::MagicBoxError;
use crate::runtime::response::Code;
use crate::runtime::result::MagicBoxResult;

/// 解析shell参数
pub(crate) fn shell_words_parse(args: &str) -> MagicBoxResult<Vec<String>> {
    let args = shellwords::split(args);
    if args.is_err() {
        return Err(MagicBoxError::new(Code::ParameterError, format!("解析参数失败: {}", args.unwrap_err().to_string()).as_str()));
    }

    Ok(args.unwrap())
}

/// 解析命令参数
pub(crate) fn parse_command_args<T: Parser + Debug>(args: &str) -> MagicBoxResult<T> {
    log::debug!("{:?}", args);

    let args = T::try_parse_from(shell_words_parse(args)?);
    if args.is_err() {
        return Err(MagicBoxError::new(Code::ParameterError, format!("解析参数失败: {}", args.unwrap_err().to_string()).as_str()));
    }

    Ok(args.unwrap())
}